import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Message } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import BranchAndTagSelect from 'components/branchAndTagSelect';
import '../index.scss';
import intl from '../../../../../../../locale';

const { pathResource } = window.FORCE;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 4,
  },

  wrapperCol: {
    span: 20,
  },
};

export default class TagModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    onCancel: PropTypes.func,
    onClose: PropTypes.func,
    formSubmit: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isModalOpen: false,
      submitting: false,
    };
  }

  componentDidMount() {
    const defaultBranch = pathResource.defaultBranch || 'master';
    this.field.setValue('ref', defaultBranch);
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });
  };

  onHandleSubmit = () => {
    if (this.state.submitting) return;
    const formData = this.field.getValues();
    this.setRefError(formData.ref);
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        this.createTag(formData);
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  nameValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 100) {
      callback(
        intl.get({
          id: 'code-assets.projectTags.containers.createTagModal.TheTagNameCannotExceed',
          defaultMessage: '标签名长度不能超过100',
        }),
      );
    }

    if (/^[0-9a-fA-F]{40}$/.test(value) === true) {
      callback(
        intl.get({
          id: 'code-assets.projectTags.containers.createTagModal.TheTagNameCannotBe',
          defaultMessage: '标签名不允许是40位且字母数字组成。',
        }),
      );
    }

    if (value.indexOf(' ') >= 0) {
      callback(
        intl.get({
          id: 'code-assets.projectTags.containers.createTagModal.TheTagNameCannotContain',
          defaultMessage: '标签名不允许包含空格',
        }),
      );
    }

    if (value.indexOf('\\') >= 0) {
      callback(
        intl.get({
          id: 'code-assets.projectTags.containers.createTagModal.TheTagNameCannotContain.1',
          defaultMessage: '标签名不允许包含\\',
        }),
      );
    }

    // const regExp = new RegExp(
    //   "[`~!@#$%^&*()=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】《》 ‘；：”“’。，、？]"
    // );
    // if (regExp.test(value) === true) {
    //   callback('非法标签名');
    // }

    // 特殊空白字符过滤
    if (encodeURIComponent(value) === '%E3%80%80') {
      callback(
        intl.get({
          id: 'code-assets.projectTags.containers.createTagModal.InvalidTagName',
          defaultMessage: '非法标签名',
        }),
      );
    }

    callback();
  };

  messageValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (value.length > 1000) {
      callback(
        intl.get({
          id: 'code-assets.projectTags.containers.createTagModal.TheDescriptionCannotExceedCharacters',
          defaultMessage: '描述长度不能超过1000',
        }),
      );
    } else {
      callback();
    }
  };

  // 创建CR
  createTag(formData) {
    exceed
      .fetch({
        api: 'project.tags.post',
        params: { projectId: pathResource.id },
        data: formData,
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.projectTags.containers.createTagModal.TagCreated',
            defaultMessage: '标签新建成功',
          }),
        });

        this.props.reload();
      })
      .fail(() => {
        this.setState({ submitting: false });
      });
  }

  onChangeRef = (value) => {
    this.field.setValue('ref', value);
    this.setRefError(value);
  };

  setRefError = (value) => {
    if (value) {
      this.field.setError('ref', '');
    } else {
      this.field.setError(
        'ref',
        intl.get({
          id: 'code-assets.projectTags.containers.createTagModal.ThisParameterIsRequired',
          defaultMessage: '该项为必填项',
        }),
      );
    }
  };

  render() {
    const { field } = this;
    const { init } = this.field;

    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            visible
            onClose={this.onClose}
            onCancel={this.onClose}
            okProps={{
              loading: this.state.submitting,
            }}
            onOk={this.onHandleSubmit}
            title={intl.get({
              id: 'code-assets.projectTags.containers.createTagModal.CreateTag',
              defaultMessage: '新建标签',
            })}
            style={{
              width: '600px',
            }}
          >
            <Form labelAlign="top" field={field} className="project-tag-form">
              <FormItem
                label={intl.get({
                  id: 'code-assets.projectTags.containers.createTagModal.TagName',
                  defaultMessage: '标签名',
                })}
                required
                {...formItemLayout}
              >
                <Input
                  autoFocus
                  spellCheck={false}
                  {...init('tag_name', {
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.projectTags.containers.createTagModal.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },
                      { validator: this.nameValidator },
                    ],
                  })}
                  placeholder={intl.get({
                    id: 'code-assets.projectTags.containers.createTagModal.EnterATagNameSuch',
                    defaultMessage: '输入标签名称，如：v1.0',
                  })}
                />
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.projectTags.containers.createTagModal.CreateSource',
                  defaultMessage: '创建来源',
                })}
                className={this.field.getState('ref') === 'error' ? 'has-error' : ''}
                required
                help={
                  this.field.getState('ref') === 'error' ? (
                    <div>
                      <YunxiaoIcon type="delete-fill" />
                      <span className="next-form-item-help-text">{this.field.getError('ref')}</span>
                    </div>
                  ) : (
                    ''
                  )
                }
                {...formItemLayout}
              >
                <BranchAndTagSelect
                  autoComplete
                  autoWidth
                  onChange={this.onChangeRef}
                  needTagSearch
                  {...this.props}
                />
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.projectTags.containers.createTagModal.Description',
                  defaultMessage: '描述信息',
                })}
                {...formItemLayout}
              >
                <Input.TextArea
                  {...init('message', {
                    rules: [{ validator: this.messageValidator }],
                  })}
                  placeholder={intl.get({
                    id: 'code-assets.projectTags.containers.createTagModal.EnterADescription',
                    defaultMessage: '请输入描述',
                  })}
                />
              </FormItem>
              <div>
                <Message
                  title={intl.get({
                    id: 'code-assets.projectTags.containers.createTagModal.Description.1',
                    defaultMessage: '说明',
                  })}
                  type="notice"
                >
                  <div>
                    {intl.get({
                      id: 'code-assets.projectTags.containers.createTagModal.ATagIsAVersion',
                      defaultMessage:
                        '标签是某一时间点上的版本，通常使用标签标识代码库的重要版本，如在项目的里程碑创建标签。',
                    })}
                  </div>
                  <div>
                    {intl.get({
                      id: 'code-assets.projectTags.containers.createTagModal.YouCanAlsoUseThe',
                      defaultMessage: "也可以使用 git 命令创建标签：git tag -a v1.0 -m '版本 1.0'",
                    })}
                  </div>
                </Message>
              </div>
            </Form>
          </Dialog>
        ) : null}
        {React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
